package com.shawn;

import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.security.Principal;
import java.util.*;

@Controller
public class OnlyController {
    private static int SIZE = 3;
    private Queue<Object> queue = new ArrayDeque<Object>();
    public SimpMessagingTemplate template;

    @Autowired
    public OnlyController(SimpMessagingTemplate template) {
        this.template = template;
    }

    @SubscribeMapping("/init/{coordinationId}")
    public Map<String,Object> init(@DestinationVariable("coordinationId") int coordinationId) {
        System.out.println("------------新用户 " + coordinationId + " 进入，空间初始化---------");
        Map<String, Object> document = new HashMap<String, Object>();
        document.put("chat",queue);
        return document;
    }

    // 广播
    @MessageMapping("/live")
    @SendTo("/topic/live")
    public TopicMessage sendTopic(TopicMessage msg) {
        if (queue.size() >= SIZE) {
            queue.poll();
        }
        queue.offer(msg);
        return msg;
    }

    // 广播 方式写点对点
    @MessageMapping("/point")
    public void sendPoint(UserMessage userMessage) {
        String dest = "/topic/point" + userMessage.getCoordinationId();
        this.template.convertAndSend(dest, userMessage);
    }

    //点对点
    @MessageMapping("/message")
   // @SendToUser(value = "/message",broadcast = false)
    public void userMessage(UserMessage userMessage,Principal pc) throws Exception {
        this.template.convertAndSendToUser(pc.getName(), "/topic/point", userMessage);
    }

    //点对点
    @MessageMapping("/real")
    @SendToUser(value = "/topic/point",broadcast = false)
    public UserMessage sendToUser(UserMessage userMessage,Principal pc) throws Exception {
        System.out.println("---- received user info: " + pc.getName());
        String real = "real " +userMessage.getMsg();
        userMessage.setMsg(real);
        return userMessage;
    }

    @GetMapping("/client")
    public String  page(){
        return "client";
    }
}